package com.dd.ms.storage.web.controller;

import com.dd.ms.common.response.ApiResponse;
import com.dd.ms.storage.web.service.internal.CosServiceImpl;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import lombok.RequiredArgsConstructor;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

/**
 * @Author liuxianmeng
 * @CreateTime 2025/6/23 1:40
 * @Description 存储服务
 */
@Api(tags = "存储服务")
@RestController
@RequiredArgsConstructor
@RequestMapping("/storage")
public class StorageController {

    private final CosServiceImpl cosServiceImpl;

    @PostMapping("/upload")
    @ApiOperation("上传文件 返回可访问（下载）的URL")
    public ApiResponse<String> upload(@ApiParam("要存储的文件")
                                      @RequestParam("file") MultipartFile file,
                                      @ApiParam("属于哪个应用（用来生成顶层文件夹名）")
                                      @RequestParam(value = "appName", required = false) String appName) {
        try {
            return ApiResponse.success(cosServiceImpl.upload(file, appName));
        } catch (Exception e) {
            return ApiResponse.error("上传失败: " + e.getMessage());
        }
    }

    @GetMapping("/url")
    @ApiOperation("获取文件的URL")
    public ApiResponse<String> getUrl(@RequestParam String key) {
        return ApiResponse.success(cosServiceImpl.getFileUrl(key));
    }

    @DeleteMapping
    @ApiOperation("删除文件")
    public ApiResponse<String> delete(@ApiParam("文件标识（唯一路径, 如：TEST/Sd-i9Oo.png）") @RequestParam String key) {
        cosServiceImpl.delete(key);
        return ApiResponse.success("删除成功");
    }
}
